<template>
  <div>
    <div>
      <a-page-header
        style="border: 1px solid rgb(235, 237, 240)"
        title="下载真题试卷"
        @back="() => $router.go(-1)"
      />
    </div>
    <a-space
      v-for="item in uploadListStore.UploadListdemo"
      :key="item.id"
      style="display: flex; flex-direction: column; margin-top: 10px"
    >
      <!-- 下载按钮 -->
      <a-button type="primary" :loading="downloadLoading" @click="handleDownload(item._id)">
        <!-- {{ downloadLoading ? '下载中...' : '下载文件' }} -->
        {{ item.originalName }}
      </a-button>

      <!-- 下载进度条（可选扩展） -->
      <a-progress v-if="progress > 0" :percent="progress" :show-info="false" style="width: 200px" />
    </a-space>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { useUploadListStore } from '@/stores/upload/upload'
import { useRoute } from 'vue-router'
const route = useRoute()
// const id = route.params.id
// console.log(id, '这是文件id')

const uploadListStore = useUploadListStore()
uploadListStore.uploadListResultAction()

const downloadLoading = ref(false)
const progress = ref(0)

const handleDownload = async (id) => {
  console.log(id, '这是文件的id')
  downloadLoading.value = true
  progress.value = 0

  try {
    const response = await axios({
      method: 'get',
      url: `http://8.138.87.146/download/${id}`,
      responseType: 'blob',
      onDownloadProgress: (progressEvent) => {
        const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        progress.value = percent
      },
    })
    console.log(response, '点击后请求到的文件数据')

    // 处理文件下载
    const blob = new Blob([response.data], {
      type: response.headers['content-type'],
    })

    const fileName =
      response.headers['content-disposition']?.split('filename=')[1]?.replace(/"/g, '') ||
      'downloaded_file'

    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    link.remove()
  } catch (error) {
    console.error('下载失败:', error)
    // 这里可以添加Ant Design的notification提示
  } finally {
    downloadLoading.value = false
    progress.value = 0
  }
}
</script>
